package com.study.task;

import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * 任务容器
 */
public class TaskContainer {

    /**
     * 任务信息
     */
    private final Map<String, TaskGroup> tasks = new ConcurrentHashMap<>();

    /**
     * 一组任务数量
     */
    private int groupRange = 200;

    /**
     * 任务总数
     */
    private int count;

    /**
     * 任务组数
     */
    private int groupNum;


    public TaskContainer(int count) {
        getTaskContainer(count);
    }

    /**
     * @param count 需要move数据
     * @return
     */
    public void getTaskContainer(int count) {
        this.count = count;
        this.groupNum = count / groupRange;
        makeTasks();
    }

    public void makeTasks() {
        IntStream.range(0, groupNum)
                .parallel()
                .forEach((i) -> {
                    TaskGroup taskGroup = new TaskGroup();
                    taskGroup.setStartIndex(i * groupRange);
                    taskGroup.setEndIndex((i + 1) * groupRange);
                    taskGroup.setId(Integer.toString(i));
                    tasks.putIfAbsent(Integer.toString(i), taskGroup);
                });
    }

    public void run() {
        List<CompletableFuture<TaskGroup>> collect = tasks.values().stream()
                .map(taskGroup -> CompletableFuture.supplyAsync(
                        () -> taskGroup.queryData()
                ))
                .collect(Collectors.toList());

        Map<String, TaskGroup> taskGroupMap = collect.stream()
                .map(CompletableFuture::join)
                .collect(Collectors.toMap(TaskGroup::getId, taskGroup -> taskGroup));

        // TODO redis

    }

}
